package ui

import (
	"embed"
	"io/fs"
	"net/http"

	"github.com/gin-gonic/gin"
)

//go:embed dist/index.html
var indexFs embed.FS

//go:embed dist/assets/*
var assetsFs embed.FS

func Registry(r *gin.Engine) {
	assets, _ := fs.Sub(assetsFs, "dist/assets")
	r.StaticFS("/assets", http.FS(assets))

	// index页面
	r.GET("", h.Index)

	// 解决刷新404问题, 解决不了刷新 URL重置问题
	r.NoRoute(h.RedirectIndex)
}

var (
	h = &HtmlHandler{}
)

type HtmlHandler struct{}

func NewHtmlHandler() *HtmlHandler {
	return &HtmlHandler{}
}

// RedirectIndex 重定向
func (h *HtmlHandler) RedirectIndex(c *gin.Context) {
	c.Redirect(http.StatusFound, "/")
}

// RedirectIndex 重定向
func (h *HtmlHandler) Index(c *gin.Context) {
	c.Header("Content-Type", "text/html;charset=utf-8")
	index, err := indexFs.ReadFile("dist/index.html")
	if err != nil {
		panic(err)
	}
	c.String(200, string(index))
}
